﻿namespace ufida.u9.ait.openapi
{
	using System;
    using System.Collections;
    using System.Collections.Generic;
	using System.Text;
    using ufida.u9.ait.openapi.utils;
    using UFIDA.U9.Base;
    using UFIDA.U9.Base.Organization;
    using UFIDA.U9.Base.UOM;
    using UFIDA.U9.CBO.Enums;
    using UFIDA.U9.CBO.MFG.BOM;
    using UFIDA.U9.CBO.MFG.CostElement;
    using UFIDA.U9.CBO.MFG.Enums;
    using UFIDA.U9.CBO.SCM.Item;
    using UFIDA.U9.CBO.SCM.ProjectTask;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Business;
    using UFSoft.UBF.Util.Context;

	/// <summary>
	/// BOMMasterSaveSV partial 
	/// </summary>	
	public partial class BOMMasterSaveSV 
	{	
		internal BaseStrategy Select()
		{
			return new BOMMasterSaveSVImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class BOMMasterSaveSVImpementStrategy : BaseStrategy
	{
		public BOMMasterSaveSVImpementStrategy() { }

		public override object Do(object obj)
		{						
			BOMMasterSaveSV bpObj = (BOMMasterSaveSV)obj;

            try
            {
				if (bpObj.Data == null || bpObj.Data.Count <= 0)
					throw new Exception("传入参数为空");

				List<CopyOfCommonArchiveDataDTOData> retlist = new List<CopyOfCommonArchiveDataDTOData>();

				foreach (var dto in bpObj.Data)
                {
					//查询维度:料号+组织+版本+项目
					string path = "";
                    if (string.IsNullOrEmpty(dto.Project?.Code))
					{
                        path = $"ItemMaster.Code='{dto.ItemMaster.Code}' and Org='{Context.LoginOrg.ID}' and BOMVersionCode='{dto.BOMVersionCode}' and Project is null";
                    }
					else
					{
                        path = $"ItemMaster.Code='{dto.ItemMaster.Code}' and Org='{Context.LoginOrg.ID}' and BOMVersionCode='{dto.BOMVersionCode}' and Project.Code='{dto.Project.Code}'";
                    }
					BOMMaster entity = BOMMaster.Finder.Find(path);
					dto.Org = new CopyOfCommonArchiveDataDTOData
					{
						ID = Context.LoginOrg.ID,
						Code = Context.LoginOrg.Code,
					};

					if(entity == null)
                    {
						//新增
						entity=BOMMasterBase.CreateDoc(dto);
						//审核
						entity=BOMMasterBase.ApproveDoc(entity);
					}
                    else
                    {
                        //修改
                        entity = BOMMasterBase.UpdateDoc(entity, dto);
                    }

					CopyOfCommonArchiveDataDTOData ret = new CopyOfCommonArchiveDataDTOData
					{
						ID = entity.ID,
						Code = entity.ItemMaster.Code,
						Name = entity.ItemMaster.Name,
					};
					retlist.Add(ret);
				}

				return ResultUtils.success(bpObj, bpObj.Data, retlist);
            }catch (Exception ex)
            {
				return ResultUtils.error(bpObj, bpObj.Data, ex);
            }
		}

    }

	#endregion
	
	
}